import {createVNode, render, resolveComponent} from "vue";
import myPopoverEl from './myPopover.vue'

const debounce = {
  mounted(el, binding) {
    // 没有绑定函数抛出错误
    if (!(binding.value instanceof Function)) {
      throw '未绑定回调函数'
    }
    let timer
    el.addEventListener('click', () => {
      if (timer) clearTimeout(timer)
      timer = setTimeout(_ => {
        binding.value()
      }, 1000)
    })
  },
  beforeUnmount(el, binding) {
    // 一次性将元素上的所有事件监听器移除
    for (const eventType of Object.keys(el)) {
      if (el[eventType] instanceof Array) {
        el[eventType].length = 0;
      }
    }
  },
}

let container;
const myPopover = {
  mounted(el, binding) {
    // 创建一个myPopoverEl虚拟节点
    const vnode = createVNode(myPopoverEl, {virtualRef: el, ...binding.value});
    // 而后创建一个容器用于渲染虚拟节点
    container = document.createElement('div');
    render(vnode, container);
    // 最后将该容器渲染到body中
    document.body.appendChild(container);
  },
  beforeUnmount() {
    // 卸载时记得将容器从body中移除
    document.body.removeChild(container);
  }
}

export default { debounce, myPopover }